import axios, { AxiosRequestConfig } from "axios";
import md5 from 'js-md5';
import router from "@/router";
import store from "@/store";
import { ElNotification } from "element-plus";
import { AESEncryption, AESDecryption } from "@/utils/crypto";
import ApiResult from "@/api/base/ApiResult";
// import { useDelCache } from "@/compositions/main/useDelCache";
store.commit("SETSECRETENABLED", (window as any).VUE_APP_URL[import.meta.env.MODE].encrypt)
store.commit("SETSECRET", '29tbgysa1pt73muq')
// store.commit("SETSECRETENABLED", 1111)
// 
const instance = axios.create({
  baseURL: (window as any).VUE_APP_URL[import.meta.env.MODE].apiBasePath,
  timeout: 60000,
} as AxiosRequestConfig);

export function navigateToLogin() {
  const fullPath = router.currentRoute.value.fullPath;
  store.commit("SETTOKEN", '');
  if (fullPath.indexOf("/login") === -1) {
    const path = sessionStorage.getItem('loginPath') || '/login'
    const route=path.split('?')[0]
    router.replace({
      path: route,
      query: { redirectUrl: encodeURIComponent(fullPath) },
    });
  }
  store.dispatch("logout", fullPath);
}

instance.interceptors.request.use(
  (config) => {

    const token = store.state.user.token;
    if (!config.headers) config.headers = {};
    config.headers.token = token;

    let str = randomString(16).toUpperCase();
    let parseMd5 = md5(str).toUpperCase();
    let timestamp = new Date().getTime()


    config.headers.noticeStr = `${parseMd5.substring(0, 8)}${str}${parseMd5.substring(parseMd5.length - 8, parseMd5.length)}`
    config.headers.timestamp = timestamp
    config.headers.sign = `${md5(str + timestamp).toUpperCase()}`


    if (store.state.insId.insId) {
      if (config.method === "post") {
        config.headers['Content-Type'] = 'application/json'
      } else if (config.method === "get") {
        config.params = {
          insId: store.state.insId.insId,
          insIds: [store.state.insId.insId],
          ...config.params,
        };
      }
    }

    return config;
  },
  (error) => {
    // 
    return Promise.resolve({
      status: 500,
      error: "请求失败,请检查网络:" + error,
    });
  }
);

instance.interceptors.response.use(
  (response) => {
    let data = response.data;
    if (!data) {
      // 
      // console.error("返回数据异常");
    }
    const secret = store.state.user.secret;
    if (secret) {
      if (data.payload && typeof data.payload == "string") {
        data.payload = JSON.parse(AESDecryption(secret, data.payload));
      }
    }
    // 
    // 登录过期
    if (data.code === 9999) {
      ElNotification.error({
        message: "登录已过期，请重新登录",
      });
      navigateToLogin();
      return;
    } else if (
      !response.config.isHidenNotice &&
      data.code !== 200 &&
      response.config.responseType != "blob"
    ) {
      ElNotification.error({
        message: data.errorMsg || "请求响应异常",
      });
    }
    return data;
  },
  (error) => {
    if (error && error.response) {
      if (error.response.status === 403) {
        navigateToLogin();
        return Promise.resolve({
          status: 500,
          error: "重新登录",
        });
      }
      if (error.response.status === 404) {
        return Promise.resolve({
          status: 500,
          error: "404接口路径不存在",
        });
      }
      if (error.response.status === 503) {
        ElNotification.error({
          message: "服务暂不可用，请稍后再试",
        });
        return Promise.resolve({
          status: 500,
          error: "服务不可用",
        });
      }
    }
    // console.error("response error:" + error);
    return Promise.resolve({
      status: 500,
      error: "请求处理失败",
    });
  }
);

function randomString(len: any) {
  let charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let randomString = '';
  for (let i = 0; i < len; i++) {
    let randomPoz = Math.floor(Math.random() * charSet.length);
    randomString += charSet.substring(randomPoz, randomPoz + 1);
  }
  return randomString;
}
// 数据加密
export async function request(
  apiPath: string,
  requestBody: any,
  params = {},
) {
  if (requestBody instanceof FormData) {
    requestBody.append("insId", store.state.insId.insId);
    requestBody.append("insIds", [store.state.insId.insId]);
  } else if (requestBody instanceof Array) {

  } else {
    requestBody = {
      insId: store.state.insId.insId,
      insIds: [store.state.insId.insId],
      ...requestBody,
    };
  }

  const secret = store.state.user.secret;
  // 处理参数格式
  if (
    store.state.user.secretEnabled &&
    secret
  ) {
    let encrypted = AESEncryption(secret, JSON.stringify(requestBody));
    return await instance.post<ApiResult<any>>(
      apiPath,
      encrypted,
      params as AxiosRequestConfig
    );
  }
  return await instance.post<ApiResult<any>>(
    apiPath,
    requestBody,
    params as AxiosRequestConfig
  );
}

export const post = instance.post;
export const get = instance.get;
